import Vue from 'vue'
import VueRouter from 'vue-router'
import ManagerUser from '../views/ManagerUser.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Layout from '../layout/Layout.vue'
import MainLayout from '../layout/MainLayout.vue'
import store from '../store/index.js'

Vue.use(VueRouter)

const routes = [
  {
    path: '/m',
    name: 'layout',
    component: Layout,
    redirect: "/commodity",
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: 'commodity',
        name: 'ManageCommodity',
        component:() => import("@/views/ManageCommodity")
      },
      {
        path: 'user',
        name: 'ManagerUser',
        component:() => import("@/views/ManagerUser")
      },
    ]
  },
  {
    path:"/",
    name:"MainLayout",
    component: MainLayout,
    redirect: "/home",
    children:[
      {
        path: 'home',
        name: "Home",
        component:() => import("@/views/Home")
      },
      {
        path: 'orders',
        name: "Orders",
        meta: {
          requiresAuth: true
        },
        component:() => import("@/views/Orders")
      },
      {
        path: 'cart',
        name: "Cart",
        meta: {
          requiresAuth: true
        },
        component:() => import("@/views/Cart")
      },
      {
        path:"userinfo",
        name:"Userinfo",
        meta: {
          requiresAuth: true
        },
        component:() => import("@/views/Userinfo")
      }
    ]
  },
  {
    path:"/login",
    name:"Login",
    component: Login,
  },
  {
    path:"/register",
    name:"Register",
    component: Register,
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const isLoggedIn = store.getters.isLoggedIn
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  if (requiresAuth && !isLoggedIn) {
    next('/login')
  } else {
    next()
  }
})
/**
 * 重复跳转问题
 */
let originPush = VueRouter.prototype.push
let originReplace = Vue.prototype.originReplace

VueRouter.prototype.push = function (location,res,rej) {

    if (res && rej ) {
        originPush.call(this,location,res,rej)
    } else {
        originPush.call(this,location,()=>{
       },()=>{
      })
    }
}

VueRouter.prototype.replace = function(location ,res,rej) {

    if (res && rej) {
        originReplace.call(this,location,res,rej)
    } else {
        originReplace.call(this,location,() => {
        },() => {
      })
    }
}
export default router
